/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    string tree2str(TreeNode* t) {
        string ans="";
        if(!t){return ans;}
        if(t->left && t->right){
            ans+=to_string(t->val)+"("+tree2str(t->left)+")"+"("+tree2str(t->right)+")";
            return ans;
        }
        else if(t->left && !t->right){
            ans+=to_string(t->val)+"("+tree2str(t->left)+")";
            return ans;
        }
        else if(!t->left && t->right){
            ans+=to_string(t->val)+"()"+"("+tree2str(t->right)+")";
            return ans;
        }
        else{
            ans+=to_string(t->val);
            return ans;
        }
        return ans;
    }
};